<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>简单聊天室</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
        }

        #chat-container {
            width: 100%;
            max-width: 800px;
            margin: 0 auto;
        }

        #message-list {
            height: 300px;
            overflow-y: scroll;
            padding: 10px;
            border: 1px solid #ccc;
            margin-bottom: 10px;
        }

        #input-container {
            display: flex;
        }

        #input-container input {
            flex: 1;
            padding: 5px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        #input-container button {
            margin-left: 10px;
            padding: 5px 10px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
    </style>
</head>

<body>
    <div id="chat-container">
        <div id="message-list"></div>
        <div id="input-container">
            <input type="text" id="message-input" placeholder="输入消息...">
            <button onclick="sendMessage()">发送</button>
        </div>
    </div>
    <script>
        function sendMessage() {
            const messageInput = document.getElementById('message-input');
            const message = messageInput.value;
            if (message) {
                const messageElement = document.createElement('div');
                sendApi(message);
                messageInput.value = ''; // 清空输入框
            } else {
                alert('请输入消息内容！'); // 提示用户输入消息内容，可根据需求自定义提示方式或样式
            }
        }
        function sendApi(message) {
            // 构造请求的URL，包含查询参数message
            // const message = 'Hello, this is a message from the frontend!';
            const encodedMessage = encodeURIComponent(message); // 对消息进行URL编码
            const url = `http://localhost:5000/messages?message=${encodedMessage}`;

            // 使用fetch API发送GET请求
            fetch(url)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    // return response.json(); // 解析JSON响应
                    return response.text(); // 解析JSON响应
                })
                .then(data => {
                    const messageList = document.getElementById('message-list');
                    messageElement.textContent = data;
                    messageList.appendChild(messageElement);
                    messageList.scrollTop = messageList.scrollHeight; // 滚动到最底部显示最新消息
                    console.log('Received messages:', data); // 在控制台打印接收到的消息历史
                })
                .catch(error => {
                    console.error('There was a problem with the fetch operation:', error);
                });
        }
    </script>
<!-- Code injected by live-server -->
<script>
	// <![CDATA[  <-- For SVG support
	if ('WebSocket' in window) {
		(function () {
			function refreshCSS() {
				var sheets = [].slice.call(document.getElementsByTagName("link"));
				var head = document.getElementsByTagName("head")[0];
				for (var i = 0; i < sheets.length; ++i) {
					var elem = sheets[i];
					var parent = elem.parentElement || head;
					parent.removeChild(elem);
					var rel = elem.rel;
					if (elem.href && typeof rel != "string" || rel.length == 0 || rel.toLowerCase() == "stylesheet") {
						var url = elem.href.replace(/(&|\?)_cacheOverride=\d+/, '');
						elem.href = url + (url.indexOf('?') >= 0 ? '&' : '?') + '_cacheOverride=' + (new Date().valueOf());
					}
					parent.appendChild(elem);
				}
			}
			var protocol = window.location.protocol === 'http:' ? 'ws://' : 'wss://';
			var address = protocol + window.location.host + window.location.pathname + '/ws';
			var socket = new WebSocket(address);
			socket.onmessage = function (msg) {
				if (msg.data == 'reload') window.location.reload();
				else if (msg.data == 'refreshcss') refreshCSS();
			};
			if (sessionStorage && !sessionStorage.getItem('IsThisFirstTime_Log_From_LiveServer')) {
				console.log('Live reload enabled.');
				sessionStorage.setItem('IsThisFirstTime_Log_From_LiveServer', true);
			}
		})();
	}
	else {
		console.error('Upgrade your browser. This Browser is NOT supported WebSocket for Live-Reloading.');
	}
	// ]]>
</script>
</body>

</html>